<template>
  <side-box :show="sideBox.recordShow" :title="sideBox.title" width="820px" @close="sideBox.recordShow =!sideBox.recordShow">
    <template slot="body">
      <div id="emailConfigSelect" class="app-container">
        <el-form ref="emailForm" v-loading="dataLoading" :model="emailForm" :rules="emailRules" class="common-form-with-desc" status-icon label-width="140px" element-loading-text="加载中...">
          <el-form-item label="SMTP服务器:" prop="host">
            <el-input v-model="emailForm.host" maxlength="60" show-word-limit autocomplete="off" />
            <span class="tip">邮件发送的服务器,如smtp.163.com</span>
          </el-form-item>
          <el-form-item label="SMTP服务器端口:" prop="smtpPort">
            <el-input-number v-model="emailForm.smtpPort" :min="1" :max="999" controls-position="right" />
            <span class="tip">SMTP服务器端口,如25</span>
          </el-form-item>
          <el-form-item label="传输协议:" prop="transportProtocol">
            <el-select v-model="emailForm.transportProtocol" placeholder="传输协议">
              <el-option v-for="item in transportProtocols" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <span class="tip">要装入session的协议（smtp、pop3、imap、nntp）</span>
          </el-form-item>
          <el-form-item label="安全协议:" prop="isSsl">
            <el-radio-group v-model="emailForm.isSsl">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
            <span class="tip" />
          </el-form-item>
          <el-form-item v-if="emailForm.isSsl==1" label="安全协议端口:" prop="smtpSslPort">
            <el-input-number v-model="emailForm.smtpSslPort" :min="1" :max="999" controls-position="right" />
            <span class="tip">若开启安全协议,务必填写端口,如465</span>
          </el-form-item>
          <el-form-item label="邮件主题:" prop="subject">
            <el-input v-model="emailForm.subject" maxlength="30" show-word-limit />
            <span class="tip">用于发送系统邮件的名称</span>
          </el-form-item>
          <el-form-item label="发邮件邮箱帐号:" prop="sendFromAddress">
            <el-input v-model="emailForm.sendFromAddress" maxlength="50" show-word-limit />
            <span class="tip">发邮件邮箱帐号</span>
          </el-form-item>
          <el-form-item label="发邮件邮箱密码:" prop="sendFromAddressPwd">
            <el-input v-model="emailForm.sendFromAddressPwd" type="password" maxlength="200" show-word-limit />
            <span class="tip">发邮件邮箱密码</span>
          </el-form-item>
          <el-form-item v-if="emailForm.id!=null" label="收件人测试邮箱:">
            <el-input v-model="toAddress" maxlength="60" show-word-limit autocomplete="off" />
          </el-form-item>
          <el-form-item v-if="emailForm.id!=null">
            <el-button :loading="testButtonLoading" @click="sendTestEmail()">发送测试邮件</el-button>
          </el-form-item>
          <el-form-item label="状态:" prop="state">
            <el-radio-group v-model="emailForm.state">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
            <span class="tip">若禁用,系统将无法发送系统邮件</span>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template slot="foot">
      <el-button :loading="sideBox.buttonLoading" type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存</el-button>
    </template>
  </side-box>
</template>
<script>
export default {
  name: 'EmailConfigSelect',
  data() {
    return {
      dataLoading: false,
      transportProtocols: [
        { value: 'smtp', label: 'smtp' },
        { value: 'pop3', label: 'pop3' }
      ],
      testButtonLoading: false,
      toAddress: '',
      emailForm: {
        host: '',
        smtpPort: '',
        transportProtocol: '',
        smtpSslPort: '',
        subject: '',
        sendFromAddress: '',
        sendFromAddressPwd: '',
        outreachInfoId: '',
        outreachInfoName: '',
        state: 1,
        isSsl: 1
      },
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create', // 对话框状态
        buttonLoading: false
      },
      emailRules: {
        host: [
          { required: true, message: '请输入SMTP服务器', trigger: 'blur' }
        ],
        smtpPort: [
          { required: true, message: '请输入SMTP服务器端口', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ],
        transportProtocol: [
          { required: true, message: '请选择传输协议', trigger: 'blur' }
        ],
        isSsl: [
          { required: true, message: '请选择是否启用安全协议', trigger: 'blur' }
        ],
        smtpSslPort: [
          { required: true, message: '请输入安全协议端口', trigger: 'blur' },
          { validator: this.commonValidate.validateNumber, trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '请输入邮件主题', trigger: 'blur' }
        ],
        sendFromAddress: [
          { required: true, message: '请输入发邮件邮箱帐号', trigger: 'blur' },
          { validator: this.commonValidate.validateEmail, trigger: 'blur' }
        ],
        sendFromAddressPwd: [
          { required: true, message: '请输入发邮件邮箱密码', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择是否启用邮件发送服务', trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {

    closeEmailConfigSelect() {
      this.sideBox.recordShow = false
    },

    init(data) {
      if (data.type === '单位') {
        this.sideBox.title = '单位邮箱网关配置'
        this.emailForm.type = '1'
      } else if (data.type === '部门') {
        this.sideBox.title = '部门邮箱网关配置'
        this.emailForm.type = '2'
      } else if (data.type === '个人') {
        this.sideBox.title = '[' + data.name + ']个人邮箱网关配置'
        this.emailForm.type = '3'
      }
      this.emailForm.outreachInfoId = data.id
      this.sideBox.recordShow = true
      this.dataLoading = true
      this.$store.dispatch('getEmailConfigByUserIdAndType', { outreachInfoId: this.emailForm.outreachInfoId, type: this.emailForm.type }).then(response => {
        if (response.length === 1) {
          this.emailForm = response[0]
          this.sideBox.status = 'update'
        } else {
          this.emailForm = { subject: data.name.substring(data.name.indexOf('[') + 1, data.name.indexOf(']')) }
          this.sideBox.status = 'create'
        }
        this.emailForm.outreachInfoId = data.id
        this.emailForm.outreachInfoName = data.name
        if (data.type === '单位') {
          this.emailForm.type = '1'
        } else if (data.type === '部门') {
          this.emailForm.type = '2'
        } else if (data.type === '个人') {
          this.emailForm.type = '3'
        }
        this.dataLoading = false
      }).catch(() => {
        this.dataLoading = false
      })
    },
    createData() {
      this.$refs['emailForm'].validate(valid => {
        if (valid) {
          this.sideBox.buttonLoading = true
          this.$store.dispatch('emailConfigSave', this.emailForm).then(response => {
            this.sideBox.buttonLoading = false
            this.msgSuccess('创建成功')
            this.sideBox.recordShow = false
          }).catch(() => {
            this.sideBox.buttonLoading = false
          })
        }
      })
    },
    updateData() {
      this.$refs['emailForm'].validate(valid => {
        if (valid) {
          this.sideBox.buttonLoading = true
          this.$store.dispatch('emailConfigUpdate', this.emailForm)
            .then(response => {
              this.sideBox.buttonLoading = false
              this.msgSuccess('创建成功')
              this.sideBox.recordShow = false
            })
            .catch(() => {
              this.sideBox.buttonLoading = false
            })
        }
      })
    },
    sendTestEmail() {
      var $this = this
      if (this.toAddress === this.emailForm.sendFromAddress) {
        this.msgWarning('不能与发件人邮箱一致')
        return
      }
      this.commonValidate.validateEmail(null, this.toAddress, function(data) {
        if (data === undefined) {
          const params = { id: $this.emailForm.id, toAddress: $this.toAddress }
          $this.testButtonLoading = true
          $this.$store.dispatch('sendTestEmail', params).then(response => {
            $this.testButtonLoading = false
            $this.msgSuccess('发送成功!')
          }).catch(() => {
            $this.testButtonLoading = false
          })
        } else {
          $this.msgWarning('请输入有效的邮箱')
        }
      })
      /**/
    }
  }
}
</script>
<style lang="scss" scoped />
